package com.xp.controller;

import com.xp.entity.User;
import com.xp.service.AuthService;
import com.xp.utils.Result;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.Valid;
import jakarta.validation.constraints.NotBlank;

/**
 * 认证控制器
 * 
 * @author AI Assistant
 * @since 2024-01-01
 */
@Slf4j
@RestController
@RequestMapping("/auth")
@RequiredArgsConstructor
@Validated
@Tag(name = "认证管理", description = "用户登录、登出、Token管理等接口")
public class AuthController {

    private final AuthService authService;

    /**
     * 用户登录
     */
    @PostMapping("/login")
    @Operation(summary = "用户登录", description = "用户通过用户名和密码进行登录认证")
    public Result<Object> login(@Valid @RequestBody LoginRequest request, HttpServletRequest httpRequest) {
        String clientIp = getClientIp(httpRequest);
        return authService.login(request.getUsername(), request.getPassword(), clientIp);
    }

    /**
     * 用户登出
     */
    @PostMapping("/logout")
    @Operation(summary = "用户登出", description = "用户登出，Token加入黑名单")
    public Result<Object> logout(HttpServletRequest request) {
        String token = extractToken(request);
        return authService.logout(token);
    }

    /**
     * 获取当前用户信息
     */
    @GetMapping("/userinfo")
    @Operation(summary = "获取用户信息", description = "根据Token获取当前登录用户的详细信息")
    public Result<User> getCurrentUser(HttpServletRequest request) {
        String token = extractToken(request);
        return authService.getCurrentUser(token);
    }

    /**
     * 刷新Token
     */
    @PostMapping("/refresh")
    @Operation(summary = "刷新Token", description = "使用当前Token获取新的Token")
    public Result<Object> refreshToken(HttpServletRequest request) {
        String token = extractToken(request);
        return authService.refreshToken(token);
    }

    /**
     * Token验证
     */
    @GetMapping("/verify")
    @Operation(summary = "验证Token", description = "验证Token的有效性")
    public Result<Object> validateToken(HttpServletRequest request) {
        String token = extractToken(request);
        boolean isValid = authService.validateToken(token);
        
        if (isValid) {
            return Result.success("Token有效");
        } else {
            return Result.error(401, "Token无效或已过期");
        }
    }

    /**
     * 从请求中提取Token
     */
    private String extractToken(HttpServletRequest request) {
        String bearerToken = request.getHeader("Authorization");
        if (bearerToken != null && bearerToken.startsWith("Bearer ")) {
            return bearerToken.substring(7);
        }
        return null;
    }

    /**
     * 获取客户端IP地址
     */
    private String getClientIp(HttpServletRequest request) {
        String xForwardedFor = request.getHeader("X-Forwarded-For");
        if (xForwardedFor != null && !xForwardedFor.isEmpty() && !"unknown".equalsIgnoreCase(xForwardedFor)) {
            return xForwardedFor.split(",")[0].trim();
        }
        
        String xRealIp = request.getHeader("X-Real-IP");
        if (xRealIp != null && !xRealIp.isEmpty() && !"unknown".equalsIgnoreCase(xRealIp)) {
            return xRealIp;
        }
        
        return request.getRemoteAddr();
    }

    /**
     * 登录请求DTO
     */
    public static class LoginRequest {
        
        @NotBlank(message = "用户名不能为空")
        @Parameter(description = "用户名", required = true)
        private String username;
        
        @NotBlank(message = "密码不能为空")
        @Parameter(description = "密码", required = true)
        private String password;

        // Getters and Setters
        public String getUsername() {
            return username;
        }

        public void setUsername(String username) {
            this.username = username;
        }

        public String getPassword() {
            return password;
        }

        public void setPassword(String password) {
            this.password = password;
        }
    }
}